import { PROXY_URL, BASE_URL, isH5 } from '@/constant/index.js'
import vuexStore from '@/store/index.js'

// 传 weekIndex 返回当前是周几
export function getWeekDay(value) {
	const weekEnum = {
		0: '周日',
		1: '周一',
		2: '周二',
		3: '周三',
		4: '周四',
		5: '周五',
		6: '周六'
	}
	if (weekEnum.hasOwnProperty(value)) return weekEnum[value]
	throw new Error(`${value} is Not a week Data`)
}
// 获取当前日期
export function getCurrentDate() {
	const date = new Date()
	const [year, month, day, hour, minutes, seconds] = [date.getFullYear(), date.getMonth() + 1, date.getDate(), date
		.getHours(), date.getMinutes(), date.getSeconds()
	]
	return `${year}-${patchZero(month)}-${patchZero(day)} ${patchZero(hour)}:${patchZero(minutes)}:${patchZero(seconds)}`
}
// toast 弹窗
export function toast({ title, time = 1000, icon = 'none' }, ...arg) {
	if (!title) return
	uni.showToast({
		title,
		icon,
		duration: time
	})
	const [callback] = arg
	if (!!callback) {
		let timeID = setTimeout(() => {
			clearTimeout(timeID)
			timeID = null
			callback()
		}, time)
	}
}
//获取当前页面
export function currentPage() {
	let pages = getCurrentPages();
	let currentPage = pages[pages.length - 1];
	return currentPage || {};
}
// 复制字符串
export function copy(str) {
	// #ifdef H5
	let aux = document.createElement("input");
	aux.setAttribute("value", str);
	document.body.appendChild(aux);
	aux.select();
	document.execCommand("copy");
	document.body.removeChild(aux);
	toast({ title: '复制成功' })
	// #endif

	// #ifndef H5
	uni.setClipboardData({
		data: str.toString(),
	}).then(() => {
		toast({ title: '复制成功' })
	})
	// #endif
}
// 拼接 0
export function patchZero(value) {
	if (isNaN(value)) return '0'
	return ('0' + value).slice(-2)
}
// 让 loading 多转一会
export function delay(time = 300) {
	return new Promise(resolve => {
		let timeID = setTimeout(() => {
			clearTimeout(timeID)
			timeID = null
			resolve()
		}, time)
	})
}


export function wxPay(options) {
	return new Promise(resolve => {
		uni.requestPayment({
			...options,
			success: () => {
				resolve([null, true])
			},
			fail: error => {
				resolve([error, null])
			}
		})
	})
}
// 上传文件
export function uploadFile(path, opt = {}) {
	return new Promise(resolve => {
		opt.header = opt?.header || {}
		const header = {
			token: vuexStore.getters.token
		}
		const url = opt.isVideo ? '/upload/video' : '/upload/image'
		uni.uploadFile({
			url: PROXY_URL + url,
			name: opt?.name || 'file',
			filePath: path,
			header: { ...header, ...opt.header },
			success: ev => {
				const { statusCode, data } = ev
				const resp = JSON.parse(data)
				if (statusCode !== 200) {
					return resolve([new Error('上传失败'), null])
				}
				const { code, data: response, msg } = resp
				toast({ title: msg })
				if (code !== 1) {
					return resolve([new Error('上传失败'), null])
				}
				if (isH5) {
					const { url } = response
					response.uri = BASE_URL + '/' + url
				}
				resolve([null, response])
			}
		})
	})
}
// 页面传值
const store = {
	data: null
}

export const setData = data => {
	store.data = data
}

export const getData = () => {
	return store.data
}
export const clearData = () => {
	store.data = null
}
// 封装并发请求
export function useConcurrence(options, maxLen, reqFunc, cb) {
	return new Promise(resolve => {
		if (!Array.isArray(options)) throw new Error('options type must be [Array]')
		const { length: MAX } = options
		let index = 0
		let count = 0
		const result = []

		async function request() {
			if (index === MAX) return
			let curIndex = index
			index++
			const { payload, hook } = options[curIndex]
			try {
				const resp = await reqFunc(...payload)
				result[curIndex] = resp
				cb && cb(resp, hook)
			} catch (error) {
				result[curIndex] = error
				cb && cb(error, hook)
			} finally {
				count++
				if (count < MAX) {
					await request()
				} else {
					resolve(result)
				}
			}
		}
		maxLen = Math.min(maxLen, MAX)
		for (let i = 0; i < maxLen; i++) {
			request()
		}
	})
}
//获取视频信息
export function getVideoInfo(src) {
	return new Promise(resolve => {
		uni.getVideoInfo({
			src,
			success: ev => resolve([null, ev]),
			fail: err => resolve([err, null])
		})
	})
}
//获取图片信息
export function getImageInfo(src) {
	return new Promise(resolve => {
		uni.getImageInfo({
			src,
			success: ev => resolve([null, ev]),
			fail: err => resolve([err, null])
		})
	})
}
// 检查对象是否存在某个key
export function checkProp(target, keyName) {
	if (typeof target !== 'object' || typeof target === 'function') throw new Error('Target must be [Object]')
	if (target.hasOwnProperty(keyName)) return target[keyName]
	return void 0
};

// 预览图片
export function previewImage(image) {
	console.log(image, 'image');
	let urls = []
	if (typeof image === 'object' && Array.isArray(image)) {
		urls = image
	} else if (typeof image === 'string') {
		urls.push(image)
	}
	uni.previewImage({
		indicator: true,
		loop: true,
		longPressActions: true,
		urls,
	})
}

// 获取url参数
export function getUrlParams(search) {
	const paramsList = search.split('&')
	if (paramsList.length === 0) return {}
	const result = {}
	paramsList.forEach(item => {
		console.log(item);
		const [key, value] = item.split('=')
		if (!!key) {
			result[key] = value
		}
	})
	return result
}

export function getTerminal() {
	let value = 0
	// #ifdef MP-WEIXIN
	value = 1
	// #endif
	// #ifdef H5
	let en = window.navigator.userAgent.toLowerCase()
	// 匹配en中是否含有MicroMessenger字符串
	if (en.match(/MicroMessenger/i) == 'micromessenger') {
		value = 2
	}
	if (en.match(/MicroMessenger/i) != 'micromessenger') {
		value = 3
	}
	// #endif
	// #ifdef APP-PLUS
	const sysInfo = uni.getSystemInfoSync()
	const platFormEnum = {
		android: 6,
		ios: 5,
	}
	value = platFormEnum[sysInfo.platform]
	// #endif

	return value
}